package com.idp.web.controller;

import com.idp.common.base.BaseController;
import com.idp.common.base.BaseResult;
import com.idp.common.constants.CommonConstants;
import com.idp.common.persistence.Page;
import com.idp.common.util.ValidateUtils;
import com.idp.web.dto.OrderIndexListDTO;
import com.idp.web.dto.OrderListDTO;
import com.idp.web.entity.Hospitals;
import com.idp.web.entity.Nurse;
import com.idp.web.entity.Orders;
import com.idp.web.service.IDoctorsService;
import com.idp.web.service.INurseService;
import com.idp.web.service.IOrdersService;
import com.idp.web.vo.DoctorSearchVo;
import com.idp.web.vo.OrderSearchVo;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 医疗订单controller
 *
 * @author xubinren
 * @version 1.0
 * @date 2018/3/6
 */
@Controller
@RequestMapping("/orders")
public class OrdersController extends BaseController {

    private Logger logger = Logger.getLogger(OrdersController.class);

    @Resource
    private IOrdersService ordersService;

    @Resource
    private INurseService nurseService;

    @Resource
    private IDoctorsService doctorsService;

    /**
     * 初始化后台管理订单查询页面
     *
     * @return
     */
    @RequestMapping("/init")
    public String init() {
        return "backstage/order/ordersSearch";
    }

    /**
     * 初始化国内医院订单查询页面
     *
     * @return
     */
    @RequestMapping("/hospitalInit")
    public String hospitalInit() {
        return "hospital/order/ordersSearch";
    }

    /**
     * 初始化护士订单查询页面
     *
     * @return
     */
    @RequestMapping("/nurseInit")
    public String nurseInit() {
        return "nurse/order/ordersSearch";
    }

    /**
     * 初始化护士首页
     *
     * @return
     */
    @RequestMapping("/nurseIndexInit")
    public String nurseIndexInit() {
        return "nurse/index/ordersSearch";
    }

    /**
     * 根据条件分页查询护士首页订单列表
     *
     * @param orderSearchVo 查询条件
     * @param page          分页信息
     * @return String
     */
    @RequestMapping("/nurseIndexInitList")
    public String nurseIndexInitList(OrderSearchVo orderSearchVo, Page<OrderIndexListDTO> page, HttpServletRequest request) {
        //页面类型
        try {
            orderSearchVo = ordersService.setOrderSearchVo(orderSearchVo,getUserType(),getUserId());
            orderSearchVo.setOrderStatus(CommonConstants.ORDER_STATUS_CONFIRM);
            request.setAttribute("page", ordersService.findIndexByPage(orderSearchVo, page));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "nurse/index/ordersList";
    }

    /**
     * 根据条件分页查询订单列表
     *
     * @param orderSearchVo 查询条件
     * @param page          分页信息
     * @return String
     */
    @RequestMapping("/list")
    public String list(OrderSearchVo orderSearchVo, Page<OrderListDTO> page, HttpServletRequest request) {
        //页面类型
        try {
            orderSearchVo = ordersService.setOrderSearchVo(orderSearchVo,getUserType(),getUserId());
            request.setAttribute("page", ordersService.findByPage(orderSearchVo, page));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return returnPage("order", "ordersList");
    }

    /**
     * 新增修改页面初始化
     *
     * @param orderSearchVo 订单条件
     * @param request       HttpServletRequest
     * @return String
     */
    @RequestMapping("/orders")
    public String orders(OrderSearchVo orderSearchVo, HttpServletRequest request) {
        try {
            orderSearchVo = ordersService.getPageType(orderSearchVo,getUserType(),getUserId());
            if (ValidateUtils.isNotEmpty(orderSearchVo.getId())) {
                Orders orders = ordersService.getById(orderSearchVo.getId());
                request.setAttribute("orders", orders);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return returnPage("order", "orders");
    }

    /**
     * 保存
     *
     * @param orders 订单信息
     * @return String
     */
    @RequestMapping("/save")
    @ResponseBody
    public String save(Orders orders) {
        JSONObject json = new JSONObject();
        try {
            // 修改
            if (ValidateUtils.isNotEmpty(orders.getId())) {
                ordersService.update(orders, getUserId());
            }
            // 新增
            else {
                ordersService.add(orders, getUserId());
            }
            json.put("result", "save_success");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "save_fail");
        }
        return json.toString();
    }

    /**
     * 查看页面初始化
     *
     * @param orderSearchVo      订单信息
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/show")
    public String show(OrderSearchVo orderSearchVo, HttpServletRequest request) {
        try {
            orderSearchVo = ordersService.setOrderSearchVo(orderSearchVo,getUserType(),getUserId());
            if (ValidateUtils.isNotEmpty(orderSearchVo.getId())) {
                Orders orders = ordersService.getById(orderSearchVo.getId());
                request.setAttribute("orders", orders);
            } else {
                logger.info("参数错误");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return returnPage("order", "ordersShow");
    }

    /**
     * 删除
     *
     * @param id 订单id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String id) {
        JSONObject json = new JSONObject();
        try {
            ordersService.delete(id);
            json.put("result", "delete_success");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "delete_fail");
        }
        return json.toString();
    }

    /**
     * 查询护士的统计信息
     *
     * @return BaseResult
     */
    @RequestMapping("/queryIndexStatistics")
    @ResponseBody
    public BaseResult queryIndexStatistics() {
        JSONObject json = new JSONObject();

        OrderSearchVo orderSearchVo = new OrderSearchVo();
        orderSearchVo = ordersService.setOrderSearchVo(orderSearchVo,getUserType(),getUserId());

        //首页汇总数据类型：1、等待确认，2、今日预约，3、等待检查，4、全部预约
        //等待确认
        orderSearchVo.setIndexType(CommonConstants.INDEX_TYPE_CONFIRM);
        json.put("indexTypeConfirm", ordersService.queryIndexStatistics(orderSearchVo));
        //今日预约
        orderSearchVo.setIndexType(CommonConstants.INDEX_TYPE_TODAY);
        json.put("indexTypeToday", ordersService.queryIndexStatistics(orderSearchVo));
        //等待检查
        orderSearchVo.setIndexType(CommonConstants.INDEX_TYPE_CHECK);
        json.put("indexTypeCheck", ordersService.queryIndexStatistics(orderSearchVo));
        //全部预约
        orderSearchVo.setIndexType(CommonConstants.INDEX_TYPE_ALL);
        json.put("indexTypeAll", ordersService.queryIndexStatistics(orderSearchVo));
        return sendResult200(json);
    }

    /**
     * 查询护士的统计信息
     *
     * @return BaseResult
     */
    @RequestMapping("/queryStatistics")
    @ResponseBody
    public BaseResult queryStatistics() {
        JSONObject json = new JSONObject();

        OrderSearchVo orderSearchVo = new OrderSearchVo();
        orderSearchVo = ordersService.setOrderSearchVo(orderSearchVo,getUserType(),getUserId());

        //全部订单
        json.put("orderAll", ordersService.queryStatistics(orderSearchVo));
        //等待确认
        orderSearchVo.setOrderStatus(CommonConstants.ORDER_STATUS_CONFIRM);
        json.put("orderConfirm", ordersService.queryStatistics(orderSearchVo));
        //等待分配
        orderSearchVo.setOrderStatus(CommonConstants.ORDER_STATUS_ASSIGN);
        json.put("orderAssign", ordersService.queryStatistics(orderSearchVo));
        //等待检查
        orderSearchVo.setOrderStatus(CommonConstants.ORDER_STATUS_CHECK);
        json.put("orderCheck", ordersService.queryStatistics(orderSearchVo));
        //等待方案
        orderSearchVo.setOrderStatus(CommonConstants.ORDER_STATUS_PROGRAM);
        json.put("orderProgram", ordersService.queryStatistics(orderSearchVo));
        //已完成
        orderSearchVo.setOrderStatus(CommonConstants.ORDER_STATUS_COMPLETED);
        json.put("orderCompleted", ordersService.queryStatistics(orderSearchVo));
        //已取消
        orderSearchVo.setOrderStatus(CommonConstants.ORDER_STATUS_CANCEL);
        json.put("orderCancel", ordersService.queryStatistics(orderSearchVo));
        return sendResult200(json);
    }

    /**
     * 确认订单
     * @param orderSearchVo 订单信息，这里只有订单id参数
     * @return BaseResult
     */
    @RequestMapping("/comfirmOrder")
    @ResponseBody
    public BaseResult comfirmOrder(OrderSearchVo orderSearchVo) {
        orderSearchVo = ordersService.setOrderSearchVo(orderSearchVo,getUserType(),getUserId());
        return ordersService.comfirmOrder(orderSearchVo);
    }

    /**
     * 取消订单
     * @param orderSearchVo 订单信息，这里只有订单id参数
     * @return BaseResult
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public BaseResult cancelOrder(OrderSearchVo orderSearchVo) {
        orderSearchVo = ordersService.setOrderSearchVo(orderSearchVo,getUserType(),getUserId());
        return ordersService.cancelOrder(orderSearchVo);
    }

    /**
     * 分配医生
     *
     * @param doctorSearch 查询信息
     * @param request      HttpServletRequest
     * @return String
     */
    @RequestMapping("/assignDoctor")
    @ResponseBody
    public BaseResult assignDoctor(DoctorSearchVo doctorSearch, HttpServletRequest request) {
        //参数验证
        if (null == doctorSearch || StringUtils.isEmpty(doctorSearch.getOrderId())){
            return sendResult400();
        }

        return ordersService.assignDoctor(doctorSearch);
    }

    /*******************************************私有方法********************************************/

    /**
     * 返回页面路径设置
     *
     * @param pageType 目标业务类型
     * @param pageAims 目标页面（去除拓展名的页面名称）
     * @return String
     */
    private String returnPage(String pageType, String pageAims) {
        Integer userType = getUserType();
        if (CommonConstants.USER_TYPE_HOSPITAL == userType) {
            //国内医院
            return "hospital/" + pageType + "/" + pageAims;
        } else if (CommonConstants.USER_TYPE_NURSE == userType) {
            //护士
            return "nurse/" + pageType + "/" + pageAims;
        }
        return "backstage/" + pageType + "/" + pageAims;
    }
}
